﻿/* Copyright (c) 2011-2012, Zetatron Consulting
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

* Neither the name of Zetatron Consulting nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Security.Cryptography;
using System.Diagnostics;

namespace AionCxxLibrary.Utilities
{
    public class Utility
    {
        public static SHA1 sha;

        public static string EncodePassword(string username, string password)
        {
            if (sha == null) sha = new SHA1Managed();
            return Utility.ToHexString(sha.ComputeHash(Encoding.UTF8.GetBytes(username.ToUpper() + ":" + password)), false);
        }

        public static string ToHexString(MemoryStream stream, bool withSpaces)
        {
            string result = "";
            long position = stream.Position;
            while (stream.Position < stream.Length)
            {
                int b = stream.ReadByte();
                result += string.Format("{0:X2}", b);
                if (withSpaces) result += " ";
            }
            stream.Position = position;
            return result;
        }

        public static string ToHexString(byte[] data, bool withSpaces)
        {
            string result = "";
            foreach(byte b in data)
            {
                result += string.Format("{0:X2}", b);
                if(withSpaces) result += " ";
            }
            return result;
        }

        public static byte[] IPAddressToByteArray(string address)
        {
            byte[] result = new byte[4];
            try
            {
                string[] data = address.Split('.');
                for (int i = 0; i < 4; i++)
                {
                    result[i] = byte.Parse(data[i]);
                }
            }
            catch(Exception e)
            {
                Log.Error("Malformed IP Address '" + address + "'", e);
            }
            return result;
        }

        public static long DateTimeToTimestamp(DateTime time)
        {
            TimeSpan t = (time - new DateTime(1970, 1, 1).ToUniversalTime());
            return (long)t.TotalSeconds;
        }

        public static long CurrentMillis()
        {
            TimeSpan t = (DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0));
            return (long)t.TotalMilliseconds;
        }

        public static void WriteServerInfo()
        {
            Log.Info("AionCxx Server Ready.\n");
            Log.Warn("WARNING: This program is not free software.");
            Log.Warn("It is a property of Zetatron Research (Copyright 2011).");
            Log.Warn("Any breach to the copyright will lead to prosecution.");
            Log.Warn("Developers : xitanium");
            Log.Warn("More information on http://www.aioncxx.net/copyright\n");
            Log.Info("Allocated Memory = " + (Process.GetCurrentProcess().PrivateMemorySize64 / 1000000) + " MB");
        }

        public static string ConvertCharacterName(string name)
        {
            return name.First().ToString().ToUpper() + name.Substring(1).ToLower().Trim();
        }

    }

    public class GUIDManager
    {
        // Below 1M = players id handled by DB
        // Above 1M = object ids (npcs, items, legions ...)
        static int IDReference = 1000000;
        static object Mutex = new object();

        public static int NextID()
        {
            lock (Mutex)
            {
                return IDReference++;
            }
        }

    }

    public class StatEntry
    {
        bool Percent = false;
        float Value = 0;

        public StatEntry(float value, bool percent)
        {
            Value = value;
            Percent = percent;
        }

        public float Apply(float value, bool direction)
        {
            float result = value;
            if (direction)
            {
                if (Percent)
                    result += (float)Math.Round((double)((result / 100) * Value));
                else
                    result += Value;
            }
            else
            {
                if (Percent)
                    result -= (float)Math.Round((double)((result / 100) * Value));
                else
                    result -= Value;
            }
            return result;
        }
    }

}
